//
//  KLRemoteVideoCell.m
//  WebRTCDemo_iOS
//
//  Created by szblsx2 on 2020/3/9.
//  Copyright © 2020 szblsx2. All rights reserved.
//

#import "KLRemoteVideoCell.h"

@interface KLRemoteVideoCell ()<RTCVideoViewDelegate>
//渲染视图
@property (nonatomic, strong) RTCEAGLVideoView *videoView;
//视频流
@property (nonatomic, strong) RTCVideoTrack *currentVideoTrack;

@end

@implementation KLRemoteVideoCell

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self addSubview:self.videoView];
        self.clipsToBounds = YES;
    }
    return self;
}

- (void)setVideoTrack:(RTCVideoTrack *)videoTrack
{
    if (_currentVideoTrack) {
        [_currentVideoTrack removeRenderer:_videoView];
    }
    _currentVideoTrack = videoTrack;
    [videoTrack addRenderer:_videoView];
}

#pragma mark - RTCVideoViewDelegate

- (void)videoView:(id<RTCVideoRenderer>)videoView didChangeVideoSize:(CGSize)size
{
    NSLog(@"videoView size:%@", NSStringFromCGSize(size));
    RTCEAGLVideoView *view = (RTCEAGLVideoView *)videoView;
    
    if (size.width > 0 && size.height > 0) {
        // Aspect fill remote video into bounds.
        CGRect bounds = view.bounds;
        CGRect videoFrame = AVMakeRectWithAspectRatioInsideRect(size, view.bounds);
        CGFloat scale = 1;
        
        if (videoFrame.size.width > videoFrame.size.height) {
            // Scale by height.
            scale = bounds.size.height / videoFrame.size.height;
        } else {
            // Scale by width.
            scale = bounds.size.width / videoFrame.size.width;
        }
        
        videoFrame.size.height *= scale;
        videoFrame.size.width *= scale;
        //        [view setBounds:(CGRect){0, 0, videoFrame.size.width, videoFrame.size.height}];
        //        [view setCenter:(CGPoint){view.center.x + (videoFrame.size.width - bounds.size.width) * 0.5, view.center.y + (videoFrame.size.height - bounds.size.height) * 0.5}];
        [view setFrame:CGRectMake(0, 0, videoFrame.size.width, videoFrame.size.height)];
        
    }
}


#pragma mark - Getter

- (RTCEAGLVideoView *)videoView
{
    if (!_videoView) {
        _videoView = [[RTCEAGLVideoView alloc] initWithFrame:self.frame];
        _videoView.delegate = self;
    }
    return _videoView;
}

@end
